import React from 'react'
const RoomConfirm = () => {
    const [searchParams] = React.Router.useSearchParams();
    const roomid =  searchParams.get('roomid') ? searchParams.get('roomid') : 0;
    const [info, SetInfo] = React.useState<any>({price: 0});
    const [dateshow, SetDateshow] = React.useState(false)
    const [guestshow, SetGuestshow] = React.useState(false)
    const [guestlist, SetGuestlist] = React.useState([])
    const [couponshow, SetCouponshow] = React.useState(false)
    const [couponlist, SetCouponlist] = React.useState<any>([])
    const [payshow, SetPayshow] = React.useState(false)
    // 价格
    const [price, SetPrice] = React.useState(0)
    // 原价
    const [originprice, SetOriginprice] = React.useState(0)
    // 天数
    const [day, SetDay] = React.useState(0)
    //支付信息
    const [paylist] = React.useState([[
        { label: '余额支付', value: 'money' },
        { label: '微信支付', value: 'wx' },
        { label: '支付宝支付', value: 'zfb' },
    ]])

    //订单信息
    const [order, SetOrder] = React.useState({
        remark: '',
        //日期
        datestr: '',
        starttime: 0,
        endtime: 0,
        //住客
        guest: '',
        gueststr: '请选择住客信息',
        guestids: [],
        //优惠券
        couponid: '',
        couponstr: '',
        //支付方式
        paystr: '余额支付',
        pay: 'money'
    })

    React.useEffect(() => {
        getRoomInfoData();
        getGuestData();
        getCouponData();
    }, [roomid])

    //当订单信息有变化，就重新计算价格
    React.useEffect(() => {
        Total()
    }, [order])

    // 计算价格
    const Total = () =>
    {
        let starttime = order.starttime
        let endtime = order.endtime

        //时间差
        let day:any = endtime - starttime;
        day = day / 86400
        day = day.toFixed(0);
        day = parseInt(day);

        //原价 时间差*房间原价
        let origin_price:any = (day * parseFloat(info.price)).toFixed(2);
        let price:any = origin_price;

        //是否有选择优惠券
        if(order.couponid)
        {
            let rate = 1;
            let list = couponlist[0]
            list.map((item:any) =>{
                if(item.value === order.couponid)
                {
                    rate = item.rate
                }
            })

            //计算折扣后的价格
            price = parseFloat((origin_price * rate).toFixed(2))
        }

        //修改价格和天数
        SetPrice(price);
        SetOriginprice(origin_price);
        SetDay(day);
    }

    // 酒店详情
    const getRoomInfoData = async() =>
    {
        let result = await React.HTTP.post('/room/info', {
            roomid: roomid,
        })

        if(result.code === 1)
        {
            SetInfo(result.data);
        }
        
    }

    // 住客信息
    const getGuestData = async() =>
    {
        let result = await React.HTTP.post('/guest/guestlist', {
            busid: React.Business.id,
        })

        if(result.code === 1)
        {
            SetGuestlist(result.data);
        }
    }

    // 优惠券列表
    const getCouponData = async() =>
    {
        let result = await React.HTTP.post('/coupon/couponlist', {
            busid: React.Business.id,
        })

        if(result.code === 1)
        {
            let data:any = [];
            result.data.map((item:any) =>{
                data.push({
                    label: `${item.coupon.title}-${item.coupon.rate*10}折`,
                    value: item.id,
                    rate: item.coupon.rate
                })
            })
            //给二维数组结构
            SetCouponlist([data]);
        }
    }

    // 日期选择
    const DateConfirm = (val:any) =>
    {
        SetDateshow(false);

        // `2025-03-17 - 2025-03-25`
        let datestr = `${new Date(val[0]).toLocaleDateString()} - ${new Date(val[1]).toLocaleDateString()}`

        //获取到开始时间和结束时间
        //标准时间转换为时间戳
        let starttime = Date.parse(new Date(val[0]).toLocaleDateString()) / 1000
        let endtime = Date.parse(new Date(val[1]).toLocaleDateString()) / 1000

        SetOrder({
            ...order,
            starttime,
            endtime,
            datestr
        })
    }

    // 住客选择
    const GuestChange = (value:any) =>
    {
        let gueststr:any = [];
        let guestids:any = [];

        //循环遍历
        guestlist.map((item:any) =>{
            if(value.includes(item.id))
            {
                gueststr.push(item.nickname)
                guestids.push(item.id)
            }
        })

        var str = gueststr.join('、')
        var ids = guestids.join(',')

        //设置订单数据
        SetOrder({
            ...order,
            gueststr: str,
            guest: ids,
            guestids
        })

    }

    // 优惠券选择
    const CouponChange = (value:any) =>
    {
        SetCouponshow(false);

        let couponstr = ''

        //获取picker第一项
        var list:any = couponlist[0]

        list.map((item:any) =>{
            if (item.value == value[0]) 
            {
                couponstr = item.label
            }
        })

        SetOrder({
            ...order,
            couponstr,
            couponid: value[0],
        })
    }

    // 支付方式 
    const PayChange = (value:any) =>
    {
        SetPayshow(false);

        let paystr = ''

        //获取picker第一项
        let list: any = paylist[0]

        list.map((item: any) => {
            if (item.value == value[0]) 
            {
                paystr = item.label
            }
        })

        SetOrder({
            ...order,
            paystr,
            pay: value[0],
        })
    }

    //订单备注
    const RemarkChange = (e:any) => 
    {
        SetOrder({
            ...order,
            remark:e
        })
    }

    const ConfirmOrder = async() =>
    {
        if(day <= 0)
        {
           return React.error('请选择入住日期')
        }

        if(order.guestids.length <= 0)
        {
            return React.error('请选择住客')
        }

        let data = {
            busid: React.Business.id,
            roomid: roomid,
            guest: order.guest,
            origin_price: originprice,
            price: price,
            starttime: order.starttime,
            endtime: order.endtime,
            couponid: order.couponid ?? '',
            remark: order.remark,
            type: order.pay
        }

        if(order.pay === 'money'){
            let result = await React.HTTP.post('/order/add', data)
            if (result.code == 1) 
            {
                React.success(result.msg, () => React.navigate(`/order/index`))
            }
            else 
            {
                React.error(result.msg)
            }
        }
        else
        {
            let result = await React.HTTP.post('/order/add', data)
            if (result.code == 1)
            {
                React.success(result.msg, () => React.navigate(`/room/pay?orderid=${result.data}`))

            }
            else 
            {
                React.error(result.msg)
            }
        }
        
    }

    return (
        <>
            <link rel="stylesheet" href="/assets/css/confirm.css" />

            <div className="skeleton">
                <div className="detail">
                    <div className="thumb">
                        <img src={info.thumb_text} alt="" />
                    </div>
                    <div className="right">
                        <p>{info.name}</p>
                        <p>￥{info.price}/ 晚</p>
                        <div className="tips">
                            {info.flag_text && info.flag_text.map((flag: any, index: any) => <span key={index}> {flag} </span>)}
                        </div>
                    </div>
                </div>

                <div className="skeleton_rect">
                    {/* 入住日期 */}
                    <div className="item">
                        <label>入住日期</label>
                        <React.UI.Input placeholder='请选择入住日期' value={order.datestr} className="item_right" onClick={() => SetDateshow(true)}/>
                    </div>
                    {/* 日期选择 */}
                    <React.UI.CalendarPicker
                        visible={dateshow}
                        selectionMode='range'
                        min={new Date()}
                        onClose={() => SetDateshow(false)}
                        onMaskClick={() => SetDateshow(false)}
                        onConfirm={DateConfirm}
                    />

                    {/* 住客信息 */}
                    <div className="item">
                        <label>住客信息</label>
                        <div className={order.guestids.length > 0 ? 'item_right' : 'item_rights'} onClick={() => SetGuestshow(true)}>
                            {order.gueststr}
                        </div>
                    </div>

                    {/* 弹出层组件 */}  
                    <React.UI.Popup
                        visible={guestshow}
                        onMaskClick={() => {SetGuestshow(false)}}
                        destroyOnClose
                        >
                            <div style={{ height: '40vh', overflowY: 'scroll', padding: '20px' }}>
                                <React.UI.CheckList
                                    multiple
                                    defaultValue={order.guestids}
                                    onChange={GuestChange}	
                                >
                                    {
                                        guestlist && guestlist.map((item:any) => (
                                            <React.UI.CheckList.Item key={item.id} value={item.id}>
                                                {item.nickname}
                                            </React.UI.CheckList.Item>
                                        ))
                                    }
                                </React.UI.CheckList>
                                <React.UI.Button color="primary" block style={{ width: '100%' }} onClick={() => SetGuestshow(false)}>确认</React.UI.Button>
                            </div>
                    </React.UI.Popup>

                </div>

                {/* 优惠券 */}
                <div className="skeleton_price">
                    <div className="tips">优惠券</div>
                    <p>{order.couponstr}</p>
                    <React.UI.Button size="mini" color="primary" onClick={() => SetCouponshow(true)}>选择</React.UI.Button>

                    {/* 弹框选项 */}
                    <React.UI.Picker
                        columns={couponlist}
                        visible={couponshow}
                        onClose={() => {
                            SetCouponshow(false)
                        }}
                        onConfirm={CouponChange}
                    />
                </div>

                {/* 支付方式 */}
                <div className="skeleton_price">
                    <div className="tips">支付方式</div>
                        <p>{order.paystr}</p>
                        <React.UI.Button size="mini" color="primary" onClick={() => SetPayshow(true)}>选择</React.UI.Button>

                        {/* 弹框选项 */}
                        <React.UI.Picker
                            columns={paylist}
                            visible={payshow}
                            onClose={() => {SetPayshow(false)}}
                            onConfirm={PayChange}
                        />
                </div>

                {/* 订单备注 */}
                <div className="skeleton_price">
                    <div className="tips">订单备注</div>
                    <React.UI.TextArea
                        defaultValue={'请输入订单备注'}
                        showCount
                        maxLength={120}
                        value={order.remark}
                        onChange={RemarkChange}
                    />
                </div>

                {/* 房间费用 */}
                <div className="skeleton_price">
                    <div className="tips">房间费用</div>
                    <div className="prices">
                        <span>￥{originprice}</span>
                        <span>共 {day} 晚</span>
                    </div>
                </div>
            </div>

            <div className="comfirm_foot_bar">
                {
                    price == originprice ? 
                    <div className="text">
                        <span>总价:</span>
                        <span>￥{price}</span>
                    </div>
                    :
                    <div className="text">
                        <span>总价:</span>
                        <span>￥{price}</span>
                        <s>原价：￥{originprice}</s>
                    </div>
                }
                
                <React.UI.Button onClick={ConfirmOrder} color='primary' shape='rounded'>提交订单</React.UI.Button>
            </div>
        </>
    )
}

export default RoomConfirm;